/****************************************************
 * Description: Controller for 应用
 * Copyright:   Copyright (c) 2018
 * Company:     xjj
 * @author      xjj
**************************************************/

package com.xjj.sso.server.controller;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xjj.framework.json.XjjJson;
import com.xjj.framework.security.annotations.SecDelete;
import com.xjj.framework.security.annotations.SecPrivilege;
import com.xjj.framework.utils.StringUtils;
import com.xjj.framework.web.SpringControllerSupport;
import com.xjj.sso.server.cache.MemCacheUtil;
import com.xjj.sso.server.cache.TicketCache;
import com.xjj.sso.server.filter.SSOHandlerSupport;
import com.xjj.sso.server.pojo.User;
import com.xjj.sso.server.ticket.GrantingTicket;
import com.xjj.sso.server.ticket.ServiceTicket;
import com.xjj.sso.server.util.SSOUtils;

@Controller
@RequestMapping("/xsso/ticket")
public class TicketController extends SpringControllerSupport {
	
	@SecPrivilege(title="最近在线用户")
	@RequestMapping("/index")
	public String index(Model model){
		
		List<GrantingTicket> gtList = TicketCache.getAllGrantingTicket();
		if(null != gtList)
		{
			Collections.sort(gtList);
		}
		model.addAttribute("gtList",gtList);
		return getViewPath("index");
	}
	
	/**
	 * 强制用户下线
	 * @param gt
	 * @return
	 */
	@RequestMapping("/kick/{gt}")
	public @ResponseBody XjjJson kick(@PathVariable("gt") String gt){
		kickUser(gt);
		return XjjJson.success("成功踢出用户");
	}
	
	
	
	/**
	 * 强制踢出用户
	 * @param user
	 */
	private void kickUser(String gt) {
		
		if(null!=gt)
		{
			GrantingTicket gtCache = TicketCache.getGrantingTicket(gt);
			
			if (null != gtCache) {
				ConcurrentHashMap<String, ServiceTicket> serviceTicketMap = gtCache
						.getServiceTicketMap();

				Collection<ServiceTicket> stes = serviceTicketMap.values();
				ServiceTicket serviceTicket = null;
				for (Iterator<ServiceTicket> iterator = stes.iterator(); iterator
						.hasNext();) {
					serviceTicket = (ServiceTicket) iterator.next();
					SSOUtils.noticeClientLogout(serviceTicket);
				}
				TicketCache.removeGrantingTicket(gt);
			}
		}
	}
	
}
